// ===============================================
// map_util
//
// Create by will on 2021/8/3 21:29
// Copyright @lankaidriver.All rights reserved.
// ===============================================

import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:url_launcher/url_launcher.dart';

import '../core_kit_localizations.dart';
import '../logger.dart';
import '../toast.dart';

enum MapType {
  aMap,
  tencent,
  biadu,
  apple,
}

class MapUtil {
  MapUtil();
  static Future<T?> showChooseMapDialog<T>({
    required BuildContext context,
    required String longitude,
    required String latitude,
    bool inApp = false,
    bool isShowTips = false,
    VoidCallback? onAppTap,
    VoidCallback? onTap,
    bool useRootNavigator = true,
    RouteSettings? routeSettings,
  }) async {
    final CoreKitS coreS = CoreKitS.of(context);
    final List<Widget> list = <Widget>[];

    if (inApp) {
      list.add(
        CupertinoActionSheetAction(
          onPressed: () {
            if (onTap != null) onTap();
            onAppTap!();
          },
          isDefaultAction: true,
          child: Text(coreS.inAppMap),
        ),
      );
    }

    if (isShowTips) {
      list
        ..add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.aMap, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.aMapTitle),
          ),
        )
        ..add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.tencent, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.tencentMapTitle),
          ),
        )
        ..add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.biadu, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.baiduMapTitle),
          ),
        );

      if (Platform.isIOS) {
        list.add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.apple, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.appleMapTitle),
          ),
        );
      }
    } else {
      if (await gotoAMap(context, longitude, latitude)) {
        list.add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.aMap, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.aMapTitle),
          ),
        );
      }

      if (await gotoTencentMap(context, longitude, latitude)) {
        list.add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.tencent, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.tencentMapTitle),
          ),
        );
      }

      if (await gotoBaiduMap(context, longitude, latitude)) {
        list.add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.biadu, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.baiduMapTitle),
          ),
        );
      }

      if (Platform.isIOS) {
        list.add(
          CupertinoActionSheetAction(
            onPressed: () async {
              if (onTap != null &&
                  await openMap(context, MapType.biadu, longitude, latitude,
                      isShowTips: isShowTips)) {
                onTap();
              }
            },
            isDefaultAction: true,
            child: Text(coreS.appleMapTitle),
          ),
        );
      }
    }

    return showCupertinoModalPopup<T?>(
      context: context,
      builder: (context) {
        return CupertinoActionSheet(
          actions: list,
          cancelButton: CupertinoActionSheetAction(
            isDestructiveAction: true,
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text(coreS.cancel),
          ),
        );
      },
      useRootNavigator: useRootNavigator,
      routeSettings: routeSettings,
    );
  }

  /// 高德地图
  static Future<bool> gotoAMap(
      BuildContext context, longitude, latitude) async {
    final String url =
        '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';
    final bool canLaunchUrl = await canLaunch(url);
    if (!canLaunchUrl) {
      CoreKitLogger().e('未检测到高德地图~');
      return false;
    }

    // await launch(url);
    return canLaunchUrl;
  }

  /// 腾讯地图
  static Future<bool> gotoTencentMap(
      BuildContext context, longitude, latitude) async {
    final String url =
        'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';
    final bool canLaunchUrl = await canLaunch(url);
    if (!canLaunchUrl) {
      CoreKitLogger().e('未检测到腾讯地图~');
      return false;
    }
    // await launch(url);
    return canLaunchUrl;
  }

  /// 百度地图
  static Future<bool> gotoBaiduMap(
      BuildContext context, longitude, latitude) async {
    final String url =
        'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';

    final bool canLaunchUrl = await canLaunch(url);
    if (!canLaunchUrl) {
      CoreKitLogger().e('未检测到百度地图~');
      return false;
    }
    // await launch(url);
    return canLaunchUrl;
  }

  /// 苹果地图
  static Future<bool> gotoAppleMap(longitude, latitude,
      {bool isShowTips = false}) async {
    final String url = 'http://maps.apple.com/?&daddr=$latitude,$longitude';
    final bool canLaunchUrl = await canLaunch(url);
    if (!canLaunchUrl) {
      CoreKitLogger().e('打开失败苹果地图~');
      return false;
    }
    // await launch(url);
    return canLaunchUrl;
  }

  /// 苹果地图
  static Future<bool> openMap(
      BuildContext context, MapType mapType, longitude, latitude,
      {bool isShowTips = false}) async {
    String url = '';
    String tips = '';
    switch (mapType) {
      case MapType.aMap:
        url =
            '${Platform.isAndroid ? 'android' : 'ios'}amap://navi?sourceApplication=amap&lat=$latitude&lon=$longitude&dev=0&style=2';
        tips = CoreKitS.of(context).aMapError;
        break;
      case MapType.tencent:
        url =
            'qqmap://map/routeplan?type=drive&fromcoord=CurrentLocation&tocoord=$latitude,$longitude&referer=IXHBZ-QIZE4-ZQ6UP-DJYEO-HC2K2-EZBXJ';

        tips = CoreKitS.of(context).tencentMapError;
        break;
      case MapType.biadu:
        url =
            'baidumap://map/direction?destination=$latitude,$longitude&coord_type=bd09ll&mode=driving';
        tips = CoreKitS.of(context).baiduMapError;
        break;
      case MapType.apple:
        url = 'http://maps.apple.com/?&daddr=$latitude,$longitude';
        break;
    }
    Navigator.pop(context);

    if (isShowTips) {
      final bool canLaunchUrl = await canLaunch(url);
      if (!canLaunchUrl) {
        if (isShowTips) {
          CoreKitToast.showError(tips);
        }
        return false;
      }
    }
    launch(url);
    return true;
  }
}
